<template>
  <div class="dashboard-container">
    <!-- 数据概览卡片 -->
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card shadow="hover" class="data-card" v-loading="userLoading" @click="goToUserPage" style="cursor: pointer;">
          <div class="data-header">
            <div class="title">总用户数</div>
            <i class="el-icon-user icon"></i>
          </div>
          <div class="data-body">
            <div class="number">{{ statistics.totalUsers }}</div>
            <div class="trend">
              <span :class="statistics.userGrowth >= 0 ? 'up' : 'down'">
                {{ statistics.userGrowth >= 0 ? '+' : '' }}{{ statistics.userGrowth }}%
              </span>
              较上周
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="data-card">
          <div class="data-header">
            <div class="title">商品总数</div>
            <i class="el-icon-goods icon"></i>
          </div>
          <div class="data-body">
            <div class="number">{{ statistics.totalGoods }}</div>
            <div class="trend">
              <span :class="statistics.goodsGrowth >= 0 ? 'up' : 'down'">
                {{ statistics.goodsGrowth >= 0 ? '+' : '' }}{{ statistics.goodsGrowth }}%
              </span>
              较上周
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="data-card" @click="goToOrderPage" style="cursor: pointer;">
          <div class="data-header">
            <div class="title">订单总数</div>
            <i class="el-icon-s-order icon"></i>
          </div>
          <div class="data-body">
            <div class="number">{{ statistics.totalOrders }}</div>
            <div class="trend">
              <span :class="statistics.orderGrowth >= 0 ? 'up' : 'down'">
                {{ statistics.orderGrowth >= 0 ? '+' : '' }}{{ statistics.orderGrowth }}%
              </span>
              较上周
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="data-card">
          <div class="data-header">
            <div class="title">交易总额</div>
            <i class="el-icon-money icon"></i>
          </div>
          <div class="data-body">
            <div class="number">¥{{ statistics.totalAmount }}</div>
            <div class="trend">
              <span :class="statistics.amountGrowth >= 0 ? 'up' : 'down'">
                {{ statistics.amountGrowth >= 0 ? '+' : '' }}{{ statistics.amountGrowth }}%
              </span>
              较上周
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="16">
        <el-card shadow="hover" v-loading="tradeLoading">
          <div slot="header">
            <span>交易趋势</span>
            <div style="float: right">
              <el-radio-group v-model="chartTimeRange" size="small" @change="updateTradeChart" style="margin-right: 10px">
                <el-radio-button label="week">本周</el-radio-button>
                <el-radio-button label="month">本月</el-radio-button>
                <el-radio-button label="year">全年</el-radio-button>
              </el-radio-group>
              <el-button 
                size="small" 
                @click="refreshTradeData"
                :loading="tradeLoading"
                style="margin-right: 10px"
                plain
              >
                <i class="el-icon-refresh"></i>
              </el-button>
              <el-button 
                size="small" 
                @click="goToOrderPage"
                plain
              >
                查看详情
              </el-button>
            </div>
          </div>
          <div class="chart" ref="tradeChart"></div>
        </el-card>
      </el-col>
      <el-col :span="8">
        <el-card shadow="hover" v-loading="categoryLoading">
          <div slot="header">
            <span>商品分类占比</span>
            <div style="float: right">
              <el-button 
                size="small" 
                @click="refreshCategoryData"
                :loading="categoryLoading"
                style="margin-right: 10px"
                plain
              >
                <i class="el-icon-refresh"></i>
              </el-button>
              <el-button 
                size="small" 
                @click="goToCategoryPage"
                plain
              >
                查看详情
              </el-button>
            </div>
          </div>
          <div class="chart" ref="categoryChart"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 最新订单 -->
    <el-card shadow="hover" class="table-card">
      <div slot="header">
        <span>最新订单</span>
        <el-button style="float: right; padding: 3px 0" @click="goToOrderPage" plain>
          查看更多
        </el-button>
      </div>
      <el-table 
        :data="latestOrders" 
        style="width: 100%" 
        v-loading="loading"
        @row-click="handleOrderRowClick"
        :row-class-name="tableRowClassName"
      >
        <el-table-column prop="orderNo" label="订单号" width="180">
          <template slot-scope="scope">
            <span class="order-link">{{ scope.row.orderNo }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="goodsName" label="商品名称" show-overflow-tooltip>
          <template slot-scope="scope">
            <span class="order-link">{{ scope.row.goodsName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="buyerNickname" label="买家" width="100">
          <template slot-scope="scope">
            {{ scope.row.buyerNickname }}
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="金额" width="120">
          <template slot-scope="scope">
            ¥{{ scope.row.amount ? scope.row.amount.toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template slot-scope="scope">
            <el-tag :type="getOrderStatusType(scope.row.status)">
              {{ getOrderStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template slot-scope="scope">
            {{ formatDateTime(scope.row.createTime) }}
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import categoryService from '@/services/category.service'
import productService from '@/services/product.service'
import orderService from '@/services/order.service'
import userService from '@/services/user.service'
import { Message } from 'element-ui'

export default {
  name: 'DashboardIndex',
  data() {
    return {
      loading: false,
      chartTimeRange: 'week',
      statistics: {
        totalUsers: 0,
        userGrowth: 0,
        totalGoods: 0,
        goodsGrowth: 0,
        totalOrders: 0,
        orderGrowth: 0,
        totalAmount: '0.00',
        amountGrowth: 0
      },
      latestOrders: [
        {
          orderNo: 'DD202401010001',
          goodsName: '二手笔记本电脑',
          amount: 2999,
          status: 'pending',
          createTime: '2024-01-01 12:00:00'
        },
        {
          orderNo: 'DD202401010002',
          goodsName: '大学教材',
          amount: 99,
          status: 'completed',
          createTime: '2024-01-01 11:30:00'
        },
        {
          orderNo: 'DD202401010003',
          goodsName: '自行车',
          amount: 599,
          status: 'shipping',
          createTime: '2024-01-01 11:00:00'
        }
      ],
      categoryData: [],
      productData: [],
      orderData: [],
      userData: [],
      charts: {},
      categoryLoading: false,
      tradeLoading: false,
      userLoading: false
    }
  },
  mounted() {
    this.fetchCategoryData()
    this.fetchProductData()
    this.fetchOrderData()
    this.fetchUserData()
    this.initCharts()
    // 监听窗口大小变化，重绘图表
    window.addEventListener('resize', this.resizeCharts)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeCharts)
  },
  methods: {
    // 获取用户数据
    async fetchUserData() {
      try {
        this.userLoading = true
        const response = await userService.getUsers()
        if (response && response.code === 200) {
          let data = response.data
          if (data && typeof data === 'object') {
            // 处理Entity Framework格式的数据
            if (data.$values && Array.isArray(data.$values)) {
              data = data.$values
            } else if (!Array.isArray(data)) {
              data = []
            }
          } else {
            data = []
          }
          
          this.userData = data || []
          console.log('获取到的用户数据:', this.userData)
          
          // 更新统计数据
          this.updateStatistics()
        } else {
          console.error('获取用户数据失败:', response)
          Message.error(response?.message || '获取用户数据失败')
        }
      } catch (error) {
        console.error('获取用户数据异常:', error)
        Message.error(error?.message || '获取用户数据失败')
      } finally {
        this.userLoading = false
      }
    },

    // 获取商品分类数据
    async fetchCategoryData() {
      try {
        this.categoryLoading = true
        const response = await categoryService.getCategories()
        if (response && response.code === 200) {
          let data = response.data
          if (data && typeof data === 'object') {
            // 处理Entity Framework格式的数据
            if (data.$values && Array.isArray(data.$values)) {
              data = data.$values
            } else if (!Array.isArray(data)) {
              data = []
            }
          } else {
            data = []
          }
          
          this.categoryData = data || []
          console.log('获取到的分类数据:', this.categoryData)
          
          // 更新图表数据
          this.updateCategoryChart()
        } else {
          console.error('获取分类数据失败:', response)
          Message.error(response?.message || '获取分类数据失败')
        }
      } catch (error) {
        console.error('获取分类数据异常:', error)
        Message.error(error?.message || '获取分类数据失败')
      } finally {
        this.categoryLoading = false
      }
    },

    // 获取商品数据
    async fetchProductData() {
      try {
        const response = await productService.getProducts()
        if (response && response.code === 200) {
          let data = response.data
          if (data && typeof data === 'object') {
            // 处理Entity Framework格式的数据
            if (data.$values && Array.isArray(data.$values)) {
              data = data.$values
            } else if (!Array.isArray(data)) {
              data = []
            }
          } else {
            data = []
          }
          
          this.productData = data || []
          console.log('获取到的商品数据:', this.productData)
          
          // 更新图表数据
          this.updateCategoryChart()
        } else {
          console.error('获取商品数据失败:', response)
          Message.error(response?.message || '获取商品数据失败')
        }
      } catch (error) {
        console.error('获取商品数据异常:', error)
        Message.error(error?.message || '获取商品数据失败')
      }
    },

    // 获取订单数据
    async fetchOrderData() {
      try {
        this.tradeLoading = true
        const response = await orderService.getOrders()
        if (response && response.code === 200) {
          let data = response.data
          if (data && typeof data === 'object') {
            // 处理Entity Framework格式的数据
            if (data.$values && Array.isArray(data.$values)) {
              data = data.$values
            } else if (!Array.isArray(data)) {
              data = []
            }
          } else {
            data = []
          }
          
          // --- 构建ID映射表以解析$ref引用 ---
          const idMap = new Map();
          this.collectIds(response, idMap); // 从原始响应数据开始收集所有ID

          // 第二次遍历订单数据，解析$ref
          const processedOrders = data.map(order => {
            // 如果订单本身是$ref，则解析它
            const actualOrder = this.resolveRef(order, idMap);
            // 解析嵌套的商品引用
            const orderProduct = this.resolveRef(actualOrder.product || actualOrder.Product, idMap);
            // 解析嵌套的买家用户引用
            const orderBuyerUser = this.resolveRef(actualOrder.user || actualOrder.User, idMap);

            // 确保 product 和 user 属性是解析后的完整对象
            return {
              ...actualOrder,
              product: orderProduct,
              Product: orderProduct, // 兼容两种命名方式
              user: orderBuyerUser,
              User: orderBuyerUser // 兼容两种命名方式
            };
          });
          
          this.orderData = processedOrders || []
          console.log('获取到的订单数据:', this.orderData)
          
          // 更新图表数据
          this.updateTradeChart()
          this.updateStatistics()
          // 更新最新订单列表
          this.updateLatestOrders()
        } else {
          console.error('获取订单数据失败:', response)
          Message.error(response?.message || '获取订单数据失败')
        }
      } catch (error) {
        console.error('获取订单数据异常:', error)
        Message.error(error?.message || '获取订单数据失败')
      } finally {
        this.tradeLoading = false
      }
    },

    // 更新最新订单列表
    updateLatestOrders() {
      if (!this.orderData || this.orderData.length === 0) {
        this.latestOrders = []
        return
      }
      
      // 处理订单数据，确保字段映射正确
      const processedOrders = this.orderData.map(order => {
        // 从订单关联的商品中获取价格
        const product = order.product || order.Product
        const price = product ? (product.price || product.Price || 0) : 0
        
        return {
          orderId: order.orderId || order.id || '未知订单',
          orderNo: order.orderId || order.id || '未知订单',
          productTitle: product?.title || product?.Title || '未知商品',
          goodsName: product?.title || product?.Title || '未知商品',
          buyerNickname: order.user?.nickname || order.User?.nickname || '未知买家',
          sellerNickname: product?.user?.nickname || product?.User?.nickname || '未知卖家',
          price: price,
          amount: price,
          status: order.status || 'pending',
          createTime: order.createTime || order.createDate,
          updateTime: order.updateTime || order.updateDate
        }
      })
      
      // 按创建时间排序，取最新的5个订单
      this.latestOrders = processedOrders
        .sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
        .slice(0, 5)
      
      console.log('最新订单列表:', this.latestOrders)
    },

    // 更新商品分类图表
    updateCategoryChart() {
      if (!this.charts.category) return
      
      // 统计每个分类的商品数量
      const categoryStats = {}
      
      // 初始化分类统计
      this.categoryData.forEach(category => {
        if (category.isUse === 1) { // 只统计启用的分类
          categoryStats[category.categoryId] = {
            name: category.name,
            count: 0,
            categoryId: category.categoryId
          }
        }
      })
      
      // 统计商品数量
      this.productData.forEach(product => {
        const categoryId = product.categoryId
        if (categoryStats[categoryId]) {
          categoryStats[categoryId].count++
        }
      })
      
      // 转换为图表数据格式
      const chartData = Object.values(categoryStats)
        .filter(item => item.count > 0) // 只显示有商品的分类
        .map((item, index) => ({
          value: item.count,
          name: item.name,
          itemStyle: { 
            color: this.getCategoryColor(index) 
          }
        }))
      
      // 如果没有数据，显示提示
      if (chartData.length === 0) {
        chartData.push({
          value: 1,
          name: '暂无商品数据',
          itemStyle: { color: '#E6A23C' }
        })
      }
      
      // 更新图例数据
      const legendData = chartData.map(item => item.name)
      
      this.charts.category.setOption({
        legend: {
          data: legendData
        },
        series: [{
          data: chartData
        }]
      })
    },

    // 更新交易趋势图表
    updateTradeChart() {
      if (!this.charts.trade) return
      
      // 根据时间范围获取数据
      const { dates, amounts, counts } = this.getTradeDataByTimeRange()
      
      this.charts.trade.setOption({
        xAxis: {
          data: dates
        },
        series: [
          {
            name: '交易金额',
            data: amounts
          },
          {
            name: '订单数量',
            data: counts
          }
        ]
      })
    },

    // 根据时间范围获取交易数据
    getTradeDataByTimeRange() {
      const now = new Date()
      let dates = []
      let amounts = []
      let counts = []
      
      if (this.chartTimeRange === 'week') {
        // 本周数据
        for (let i = 6; i >= 0; i--) {
          const date = new Date(now)
          date.setDate(date.getDate() - i)
          const dateStr = this.formatDate(date)
          dates.push(dateStr)
          
          // 统计当天的订单
          const dayOrders = this.orderData.filter(order => {
            const orderDate = new Date(order.createTime)
            return this.isSameDay(orderDate, date)
          })
          
          const dayAmount = dayOrders.reduce((sum, order) => {
            // 从订单关联的商品中获取价格
            const product = order.product || order.Product
            const price = product ? (product.price || product.Price || 0) : 0
            return sum + price
          }, 0)
          amounts.push(dayAmount)
          counts.push(dayOrders.length)
        }
      } else if (this.chartTimeRange === 'month') {
        // 本月数据（按周统计）
        const weeks = this.getWeeksInMonth(now)
        dates = weeks.map(week => week.label)
        amounts = weeks.map(week => {
          const weekOrders = this.orderData.filter(order => {
            const orderDate = new Date(order.createTime)
            return orderDate >= week.start && orderDate <= week.end
          })
          return weekOrders.reduce((sum, order) => {
            // 从订单关联的商品中获取价格
            const product = order.product || order.Product
            const price = product ? (product.price || product.Price || 0) : 0
            return sum + price
          }, 0)
        })
        counts = weeks.map(week => {
          const weekOrders = this.orderData.filter(order => {
            const orderDate = new Date(order.createTime)
            return orderDate >= week.start && orderDate <= week.end
          })
          return weekOrders.length
        })
      } else if (this.chartTimeRange === 'year') {
        // 全年数据（按月统计）
        for (let i = 11; i >= 0; i--) {
          const date = new Date(now.getFullYear(), now.getMonth() - i, 1)
          const monthStr = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`
          dates.push(monthStr)
          
          const monthOrders = this.orderData.filter(order => {
            const orderDate = new Date(order.createTime)
            return orderDate.getFullYear() === date.getFullYear() && 
                   orderDate.getMonth() === date.getMonth()
          })
          
          const monthAmount = monthOrders.reduce((sum, order) => {
            // 从订单关联的商品中获取价格
            const product = order.product || order.Product
            const price = product ? (product.price || product.Price || 0) : 0
            return sum + price
          }, 0)
          amounts.push(monthAmount)
          counts.push(monthOrders.length)
        }
      }
      
      return { dates, amounts, counts }
    },

    // 获取月份中的周数据
    getWeeksInMonth(date) {
      const year = date.getFullYear()
      const month = date.getMonth()
      const firstDay = new Date(year, month, 1)
      const lastDay = new Date(year, month + 1, 0)
      const weeks = []
      
      let currentWeek = 1
      let currentDate = new Date(firstDay)
      
      while (currentDate <= lastDay) {
        const weekStart = new Date(currentDate)
        const weekEnd = new Date(currentDate)
        weekEnd.setDate(weekEnd.getDate() + 6)
        
        if (weekEnd > lastDay) {
          weekEnd.setTime(lastDay.getTime())
        }
        
        weeks.push({
          label: `第${currentWeek}周`,
          start: weekStart,
          end: weekEnd
        })
        
        currentDate.setDate(currentDate.getDate() + 7)
        currentWeek++
      }
      
      return weeks
    },

    // 判断是否为同一天
    isSameDay(date1, date2) {
      return date1.getFullYear() === date2.getFullYear() &&
             date1.getMonth() === date2.getMonth() &&
             date1.getDate() === date2.getDate()
    },

    // 格式化日期
    formatDate(date) {
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${month}-${day}`
    },

    // 更新统计数据
    updateStatistics() {
      // 计算总用户数
      this.statistics.totalUsers = this.userData.length
      
      // 计算总订单数
      this.statistics.totalOrders = this.orderData.length
      
      // 计算总交易金额 - 从订单关联的商品中获取价格
      this.statistics.totalAmount = this.orderData
        .reduce((sum, order) => {
          // 从订单关联的商品中获取价格
          const product = order.product || order.Product
          const price = product ? (product.price || product.Price || 0) : 0
          return sum + price
        }, 0)
        .toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })
      
      // 计算总商品数
      this.statistics.totalGoods = this.productData.length
      
      // 计算增长率（这里使用简单的模拟数据）
      this.statistics.userGrowth = Math.floor(Math.random() * 20) - 10
      this.statistics.orderGrowth = Math.floor(Math.random() * 20) - 10
      this.statistics.amountGrowth = Math.floor(Math.random() * 20) - 10
      this.statistics.goodsGrowth = Math.floor(Math.random() * 20) - 10
    },

    // 获取分类颜色
    getCategoryColor(index) {
      const colors = [
        '#409EFF', // 蓝色
        '#67C23A', // 绿色
        '#E6A23C', // 橙色
        '#F56C6C', // 红色
        '#909399', // 灰色
        '#9C27B0', // 紫色
        '#FF9800', // 深橙色
        '#4CAF50', // 浅绿色
        '#2196F3', // 浅蓝色
        '#FF5722'  // 深红色
      ]
      return colors[index % colors.length]
    },

    // 跳转到商品分类页面
    goToCategoryPage() {
      this.$router.push({
        path: '/goods/category',
        query: { from: 'dashboard' }
      })
    },

    // 跳转到订单列表页面
    goToOrderPage() {
      this.$router.push({
        path: '/order',
        query: { from: 'dashboard' }
      })
    },

    // 跳转到用户列表页面
    goToUserPage() {
      this.$router.push({
        path: '/user',
        query: { from: 'dashboard' }
      })
    },

    async refreshCategoryData() {
      this.categoryLoading = true
      try {
        await Promise.all([
          this.fetchCategoryData(),
          this.fetchProductData()
        ])
      } catch (error) {
        console.error('刷新数据失败:', error)
        Message.error(error?.message || '刷新数据失败')
      } finally {
        this.categoryLoading = false
      }
    },

    async refreshTradeData() {
      this.tradeLoading = true
      try {
        await this.fetchOrderData()
      } catch (error) {
        console.error('刷新交易数据失败:', error)
        Message.error(error?.message || '刷新交易数据失败')
      } finally {
        this.tradeLoading = false
      }
    },

    async refreshUserData() {
      this.userLoading = true
      try {
        await this.fetchUserData()
      } catch (error) {
        console.error('刷新用户数据失败:', error)
        Message.error(error?.message || '刷新用户数据失败')
      } finally {
        this.userLoading = false
      }
    },

    initCharts() {
      // 初始化交易趋势图表
      const tradeChart = echarts.init(this.$refs.tradeChart)
      tradeChart.setOption({
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            let result = params[0].axisValue + '<br/>'
            params.forEach(param => {
              if (param.seriesName === '交易金额') {
                result += param.marker + param.seriesName + ': ¥' + param.value.toLocaleString() + '<br/>'
              } else {
                result += param.marker + param.seriesName + ': ' + param.value + '单<br/>'
              }
            })
            return result
          }
        },
        legend: {
          data: ['交易金额', '订单数量']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: []
        },
        yAxis: [
          {
            type: 'value',
            name: '金额',
            axisLabel: {
              formatter: '¥{value}'
            }
          },
          {
            type: 'value',
            name: '订单数',
            axisLabel: {
              formatter: '{value}单'
            }
          }
        ],
        series: [
          {
            name: '交易金额',
            type: 'line',
            smooth: true,
            data: []
          },
          {
            name: '订单数量',
            type: 'line',
            smooth: true,
            yAxisIndex: 1,
            data: []
          }
        ]
      })

      // 添加点击事件
      tradeChart.on('click', (params) => {
        console.log('点击了交易趋势图表:', params)
        this.goToOrderPage()
      })

      // 初始化商品分类占比图表
      const categoryChart = echarts.init(this.$refs.categoryChart)
      categoryChart.setOption({
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 10,
          data: []
        },
        series: [
          {
            name: '商品分类',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '20',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: []
          }
        ]
      })

      // 添加点击事件
      categoryChart.on('click', (params) => {
        console.log('点击了分类:', params.name)
        this.goToCategoryPage()
      })

      this.charts = {
        trade: tradeChart,
        category: categoryChart
      }
      
      // 如果有数据，立即更新图表
      if (this.categoryData.length > 0 || this.productData.length > 0) {
        this.updateCategoryChart()
      }
      if (this.orderData.length > 0) {
        this.updateTradeChart()
      }
    },
    resizeCharts() {
      Object.values(this.charts).forEach(chart => {
        chart && chart.resize()
      })
    },
    getOrderStatusType(status) {
      const statusMap = {
        pending: 'warning',
        shipping: 'primary',
        completed: 'success',
        cancelled: 'info'
      }
      return statusMap[status] || 'info'
    },
    getOrderStatusText(status) {
      const statusMap = {
        pending: '待确认',
        confirmed: '已确认',
        completed: '已完成',
        cancelled: '已取消'
      }
      return statusMap[status] || '未知'
    },
    handleOrderRowClick(row) {
      console.log('点击了订单:', row.orderNo)
      this.goToOrderPage()
    },
    tableRowClassName({ row }) {
      const status = row.status
      if (status === 'pending') {
        return 'pending-row'
      } else if (status === 'completed') {
        return 'completed-row'
      } else if (status === 'cancelled') {
        return 'cancelled-row'
      }
      return ''
    },
    formatDateTime(dateTime) {
      if (!dateTime) return ''
      const date = new Date(dateTime)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    },
    // 辅助函数：递归地收集所有带有$id的对象 (从list.vue复制)
    collectIds(obj, map) {
      if (typeof obj === 'object' && obj !== null) {
        if (obj.$id) {
          map.set(obj.$id, obj);
        }
        // 如果是数组，则遍历每个元素
        if (Array.isArray(obj)) {
          obj.forEach(item => this.collectIds(item, map)); // 递归调用自身
        } else { // 如果是对象，则遍历其属性
          for (const key in obj) {
            if (Object.prototype.hasOwnProperty.call(obj, key)) {
              this.collectIds(obj[key], map); // 递归调用自身
            }
          }
        }
      }
    },

    // 辅助函数：解析$ref引用 (从list.vue复制)
    resolveRef(obj, idMap) {
      if (typeof obj === 'object' && obj !== null && obj.$ref) {
        const refId = obj.$ref;
        const resolved = idMap.get(refId);
        if (resolved) {
          return resolved;
        } else {
          console.warn(`resolveRef: 未能在ID映射中找到引用 ${refId} 对应的对象`);
          return obj; // 如果未找到，返回原始对象
        }
      }
      return obj; // 不是$ref，直接返回
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 20px;

  .data-card {
    .data-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      .title {
        font-size: 16px;
        color: #666;
      }

      .icon {
        font-size: 24px;
        color: #409EFF;
      }
    }

    .data-body {
      .number {
        font-size: 24px;
        font-weight: bold;
        margin-bottom: 10px;
      }

      .trend {
        font-size: 14px;
        color: #666;

        .up {
          color: #67C23A;
          margin-right: 5px;
        }

        .down {
          color: #F56C6C;
          margin-right: 5px;
        }
      }
    }
  }

  .chart-row {
    margin-top: 20px;
    margin-bottom: 20px;

    .chart {
      height: 350px;
    }
  }

  .table-card {
    margin-top: 20px;

    .order-link {
      color: #409EFF;
      cursor: pointer;
      text-decoration: none;
      
      &:hover {
        color: #66b1ff;
        text-decoration: underline;
      }
    }

    .pending-row {
      background-color: #fdf6ec;
      
      &:hover {
        background-color: #f5e6c3;
      }
    }

    .completed-row {
      background-color: #f0f9ff;
      
      &:hover {
        background-color: #e1f3ff;
      }
    }

    .cancelled-row {
      background-color: #fef0f0;
      
      &:hover {
        background-color: #fde2e2;
      }
    }
  }
}
</style> 